<script setup lang="ts">
import { nextTick, shallowRef } from "vue";
import { useEffect } from "@/framework/vue/hooks";

/* 监听元素尺寸变化 */

defineOptions({ name: "resize-observer" });
const emits = defineEmits({
  ready: () => true,
});

const element = shallowRef<HTMLDivElement>();
const rect = shallowRef<DOMRectReadOnly>();

useEffect(() => {
  const el = element.value;
  if (el) {
    // let timeoutId: any;
    rect.value = el.getBoundingClientRect();
    nextTick(() => emits("ready"));

    const observer = new ResizeObserver(entries => {
      // console.log("resize", entries.at(-1)!.contentRect.height);
      // clearTimeout(timeoutId);
      // timeoutId = setTimeout(() => {
      //   const entry = entries[entries.length - 1];
      //   rect.value = entry.contentRect;
      // }, 100);

      const entry = entries[entries.length - 1];
      rect.value = entry.contentRect;
    });
    observer.observe(el);
    return () => {
      observer.unobserve(el);
      observer.disconnect();
    };
  }
});
</script>

<template>
  <div ref="element" class="resize-observer">
    <slot v-if="rect" :width="rect.width" :height="rect.height" />
  </div>
</template>

<style lang="less">
.resize-observer {
  width: 100%;
  max-width: 100%;
  height: 100%;
  max-height: 100%;
  box-sizing: border-box;
}
</style>
